# -*- coding: utf-8 -*-

"""
 (c) 2023 - Copyright CTyunOS Inc

 Authors:
   youyifeng <youyf2@chinatelecom.cn>

"""
import logging

from cve_ease.helper import notifier_timestamp

from .base import NotifierBase

logger = logging.getLogger('cve-ease')


class MailQQ(NotifierBase):
    """
    MailQQ notifier
    """

    def __init__(self, gconfig):
        self._name = 'mailqq_notifier'
        self._config = gconfig
        # setting wanip
        if not hasattr(gconfig, 'WANIP'):
            from cve_ease.helper import get_wanip
            self._wanip = get_wanip()
        else:
            self._wanip = gconfig.WANIP
        # setting watcher
        self._watcher = None
        if hasattr(gconfig, 'WATCHER'):
            self._watcher = gconfig.WATCHER
        # setting notify timestamp
        self._notify_time = notifier_timestamp()

    def do_send(self, data):
        import smtplib
        from email.mime.text import MIMEText

        subject = f"openEuler/cve-ease播报群"
        sender = self._mail_sender
        password = self._mail_smtp_token

        content = data
        recver = self._mail_recver
        message = MIMEText(content, "plain", "utf-8")

        message['Subject'] = subject
        message['To'] = recver
        message['From'] = sender

        try:
            smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)
            smtp.login(sender, password)
            smtp.sendmail(sender, [recver], message.as_string())
            smtp.close()
        except Exception as e:
            print("[+] mailqq send failed!", str(e))
            exit(1)
        print('[+] mailqq send ok!')

    def send_text(self, msg="", debug=False):
        if debug:
            print(msg)
        self.do_send(msg)

    def check_enabled(self):
        return False
        if 'enabled' not in self._config.config['mailqq'] or "1" != self._config.config['mailqq']['enabled']:
            logger.debug(' * mailqq notifier is not enabled')
            return False
        return True

    def do_update_nofity(self, info_diff: dict, info_type: str):
        return

        logger.debug(" mailqq do_update_notify")

        self.send_text(self.pretty_cve_udpate(diff))

    def do_status_notify(self, info_list: list, info_type: str):
        return

    def pretty_cve_record(self, record):
        return (
                "评分:[{}] {}\n" +
                " 包名: {}\n" +
                " 发布时间: {}\n" +
                " https://www.openeuler.org/zh/security/cve/detail/?cveId={}&packageName={}\n"
        ).format(
            record["cvsssCoreNVD"] if record["cvsssCoreNVD"] else record["cvsssCoreOE"],
            record["cveId"],
            record["packageName"],
            record["updateTime"],
            record["cveId"],
            record["packageName"],
        )

    def pretty_cve_udpate(self, diff):
        message = (
                "Msg from CVE-EASE: \n" +
                " {}\n" +
                "服务状态: OK\n" +
                "服务IP: {}\n" +
                "CVE记录总数: {}\n" +
                "更新情况:\n" +
                " 新增:{}" +
                " 修改:{}" +
                " 删减:{}\n" +
                "Top{}变更信息概况:\n" +
                "\n"
        ).format(
            self._notify_time,
            self.wanip,
            len(diff["data"]),
            len(diff["add"]),
            len(diff["modify"]),
            len(diff["delete"]),
            self._config.NOTIFIER_RECORD_NUM
        )
        count = int(self._config.NOTIFIER_RECORD_NUM)
        addlist = sorted(diff["add"], key=lambda d: d['id'])
        modifylist = sorted(diff["modify"], key=lambda d: d['id'])
        dellist = sorted(diff["delete"], key=lambda d: d['id'])

        need_output_record_list = addlist + modifylist + dellist
        for r in need_output_record_list[:count]:
            message += self.pretty_cve_record(r)

        message += """\n相关同事请务必及时修复漏洞，杜绝隐患保障系统安全。\n"""
        return message

    def do_sa_notifier(self, diff):
        """
            diff = {
                "modify": [],
                "add": [],
                "delete": [],
                "data": [],
            }
        :param diff:
        :return:
        """
        if not self.check_enabled():
            return

        logger.debug(" mailqq do_sa_notifier")

        self.send_text(self.pretty_sa_udpate(diff))

    def pretty_sa_record(self, record):
        return (
                "编号:{}\n" +
                " 包名: {}\n" +
                " CVEID: {}\n" +
                " 发布时间: {}\n" +
                " https://www.openeuler.org/zh/security/safety-bulletin/detail/?id={}\n"
        ).format(
            record["securityNoticeNo"],
            record["affectedComponent"],
            record["cveId"],
            record["updateTime"],
            record["securityNoticeNo"],
        )

    def pretty_sa_udpate(self, diff):
        message = (
                "Msg from CVE-EASE: \n" +
                " {}\n" +
                "服务状态: OK\n" +
                "服务IP: {}\n" +
                "SA记录总数: {}\n" +
                "更新情况:\n" +
                " 新增:{}" +
                " 修改:{}" +
                " 删减:{}\n" +
                "Top{}变更信息概况:\n" +
                "\n"
        ).format(
            self._notify_time,
            self.wanip,
            len(diff["data"]),
            len(diff["add"]),
            len(diff["modify"]),
            len(diff["delete"]),
            self._config.NOTIFIER_RECORD_NUM
        )
        count = int(self._config.NOTIFIER_RECORD_NUM)
        addlist = sorted(diff["add"], key=lambda d: d['id'])
        modifylist = sorted(diff["modify"], key=lambda d: d['id'])
        dellist = sorted(diff["delete"], key=lambda d: d['id'])

        need_output_record_list = addlist + modifylist + dellist
        for r in need_output_record_list[:count]:
            message += self.pretty_sa_record(r)

        message += """\n相关同事请务必及时修复漏洞，杜绝隐患保障系统安全。\n"""
        return message

    def do_update_notify(self, info_diff: dict, info_type: str):
        """
        更新播报
        :param info_diff:
        :param info_type:
        :return:
        """
        for w in self._watcher:
            cw = self._watcher[w]
            if self._name not in cw:
                continue

    def do_status_notify(self, info_list: list, info_type: str):
        """
        状态播报
        :param info_list:
        :param info_type:
        :return:
        """
        for w in self._watcher:
            cw = self._watcher[w]
            if self._name not in cw:
                continue
